package com.association.main.controller;

import com.association.main.common.R;
import com.association.main.dao.MembersDao;
import com.association.main.domain.Clubs;
import com.association.main.domain.JoinInfo;
import com.association.main.domain.Members;
import com.association.main.dto.MembersDto;
import com.association.main.service.ClubsService;
import com.association.main.service.JoinInfoService;
import com.association.main.service.MembersService;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import javafx.util.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/members")
public class MembersController {
    @Autowired
    private MembersService membersService;

    @Autowired
    private ClubsService clubsService;

    @Autowired
    private JoinInfoService joinInfoService;
    @GetMapping
    public R<Page> memberList(int page, int pageSize, Members members, Integer clubId, HttpServletRequest request) {
        // 创建分页对象
        Page<MembersDto> pageInfo = new Page<>(page, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Members> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(members.getUsername())) {
            queryWrapper.like(Members::getUsername, members.getUsername());
        }
        if (StringUtils.isNotBlank(members.getName())) {
            queryWrapper.like(Members::getName, members.getName());
        }

        // 执行查询
        List<Members> membersList = membersService.list(queryWrapper);

        // 处理数据
        List<MembersDto> membersDtos = membersList.stream().map(m -> {
            MembersDto membersDto = new MembersDto();
            BeanUtils.copyProperties(m, membersDto);

            // 查询参加的社团信息
            LambdaQueryWrapper<JoinInfo> joinInfoWrapper = new LambdaQueryWrapper<>();
            joinInfoWrapper.eq(JoinInfo::getMemberId, m.getId());
            if (clubId != null) {
                joinInfoWrapper.eq(JoinInfo::getClubId, clubId);
            }
            List<JoinInfo> joinInfoList = joinInfoService.list(joinInfoWrapper);
            List<Clubs> clubs = joinInfoList.stream().map(j -> clubsService.getById(j.getClubId())).collect(Collectors.toList());
            membersDto.setClubs(clubs);

            return membersDto;
        }).collect(Collectors.toList());

        // 筛选参加指定社团的成员
        if (clubId != null) {
            membersDtos = membersDtos.stream().filter(m -> !m.getClubs().isEmpty()).collect(Collectors.toList());
        }

        // 处理权限问题
        String token = request.getHeader("token");
        String userType = JwtUtil.getUserType(token);
        if ("member".equals(userType)) {
            Integer userId = JwtUtil.getUserId(token);
            LambdaQueryWrapper<Clubs> clubsWrapper = new LambdaQueryWrapper<>();
            clubsWrapper.eq(Clubs::getCreatedBy, userId);
            List<Clubs> clubsList = clubsService.list(clubsWrapper);
            membersDtos = membersDtos.stream().filter(m -> clubsList.stream().anyMatch(c -> m.getClubs().contains(c))).collect(Collectors.toList());
        }

        // 设置分页数据
        pageInfo.setRecords(membersDtos);

        return R.success(pageInfo);
    }


    @PostMapping
    @Transactional
    public R<String> add(@RequestBody Map data){
        Members members=new Members();
        members.setUsername((String) data.get("username"));
        members.setPassword((String) data.get("password"));
        members.setEmail((String) data.get("email"));
        members.setPhone((String) data.get("phone"));
        members.setSex((String) data.get("sex"));
        members.setName((String) data.get("name"));
        members.setId((Integer) data.get("id"));
        members.setCreatedAt(LocalDateTime.now());
        members.setUpdatedAt(LocalDateTime.now());
        membersService.save(members);
        //做添加操作，返回的members的ID
        Integer id = members.getId();
        List<Map<String, Integer>> clublistData = (List<Map<String, Integer>>) data.get("clubs");
        if(clublistData.size()>0){
            List<Map<String, Integer>> distinctClublistData = clublistData.stream()
                    .collect(Collectors.toMap(
                            map -> map.get("id"),  // 根据id属性进行分组
                            map -> map,  // 如果有重复id，则保留第一个元素
                            (map1, map2) -> map1,  // 合并函数：如果有重复id，保留第一个元素
                            LinkedHashMap::new  // 保留插入顺序
                    ))
                    .values()
                    .stream()
                    .collect(Collectors.toList());
            //提取出来所属社团，然后进行添加
            List<JoinInfo> joinInfos=new ArrayList<>();
            log.info(clublistData+"");
            for(int i=0;i<distinctClublistData.size();i++){
                JoinInfo joinInfo=new JoinInfo();
                joinInfo.setMemberId(id);
                joinInfo.setClubId(distinctClublistData.get(i).get("id"));
                joinInfos.add(i,joinInfo);
            }
            joinInfoService.saveBatch(joinInfos);
        }


//        membersService.save(members);
        return R.success(20000,"添加成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestBody Members members,HttpServletRequest request){
        String token = request.getHeader("token");
        String userType = JwtUtil.getUserType(token);
        if(userType.equals("member")){
            return R.error("删除失败,无权限删除用户");
        }
        membersService.removeById(members.getId());
        return R.success(20000,"删除成功");
    }

    @PutMapping
    @Transactional
    public R<String> update(@RequestBody Map data){
        Members members=new Members();
        members.setUsername((String) data.get("username"));
        members.setPassword((String) data.get("password"));
        members.setEmail((String) data.get("email"));
        members.setPhone((String) data.get("phone"));
        members.setSex((String) data.get("sex"));
        members.setName((String) data.get("name"));
        members.setId((Integer) data.get("id"));
        membersService.updateById(members);
        //先更新用户表
        //以下是更新用户-社团表
        LambdaUpdateWrapper<JoinInfo> joinInfoLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        joinInfoLambdaUpdateWrapper.eq(JoinInfo::getMemberId,members.getId());
        joinInfoService.remove(joinInfoLambdaUpdateWrapper);
        //以上是移除join的信息
        List<Map<String, Integer>> clublistData = (List<Map<String, Integer>>) data.get("clubs");
        //以上是获取全部参数
        List<Map<String, Integer>> distinctClublistData = clublistData.stream()
                .collect(Collectors.toMap(
                        map -> map.get("id"),  // 根据id属性进行分组
                        map -> map,  // 如果有重复id，则保留第一个元素
                        (map1, map2) -> map1,  // 合并函数：如果有重复id，保留第一个元素
                        LinkedHashMap::new  // 保留插入顺序
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
        List<JoinInfo> joinInfos=new ArrayList<>();
        for(int i=0;i<distinctClublistData.size();i++){
            JoinInfo joinInfo=new JoinInfo();
            joinInfo.setMemberId(members.getId());
            joinInfo.setClubId(distinctClublistData.get(i).get("id"));
            joinInfos.add(i,joinInfo);
        }
        //前面是移除，现在是添加
        joinInfoService.saveBatch(joinInfos);
        return R.success(20000,"更新成功");
    }


    @PutMapping("/out")
    public R<String> outData(@RequestBody Map data){
        Integer clubs = (Integer)data.get("clubs");
        Integer id = (Integer) data.get("id");
        LambdaQueryWrapper<JoinInfo>  joinInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getClubId,clubs);
        joinInfoLambdaQueryWrapper.eq(JoinInfo::getMemberId,id);
        boolean remove = joinInfoService.remove(joinInfoLambdaQueryWrapper);
        return remove?R.success("退出成功"):R.error("操作失败");
    }

}
